package com.example.fashionshoes.controller.user;

import com.example.fashionshoes.constant.JwtConst;
import com.example.fashionshoes.exception.BusinessException;
import com.example.fashionshoes.pojo.po.Order;
import com.example.fashionshoes.pojo.po.Result;
import com.example.fashionshoes.pojo.vo.OrderDetailVo;
import com.example.fashionshoes.pojo.vo.OrderVo;
import com.example.fashionshoes.pojo.vo.ToPayVo;
import com.example.fashionshoes.service.OrderService;
import com.example.fashionshoes.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrderService orderService;

    /**
     * 生成订单-结算页
     * @return 地址簿和商品
     */
    @GetMapping("/pre")
    public Result<ToPayVo> getCheckOutInfo(){
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get(JwtConst.USER_ID);
        ToPayVo toPayVo;
        try {
            toPayVo = orderService.getCheckOutInfo(userId);
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        }
        return Result.success(toPayVo);
    }

    /**
     * 生成订单
     * @param order 参数
     * @return 生成的订单
     */
    @PostMapping
    public Result<OrderVo> toPay(@RequestBody Order order){
        OrderVo orderVo;
        try {
            orderVo = orderService.toPay(order);
        } catch (BusinessException e) {
            return Result.error("你似乎还没有添加地址");
        }
        return Result.success(orderVo);
    }

    /**
     * 获取订单列表
     * @return 订单列表
     */
    @GetMapping
    public  Result<List<OrderVo>> list(){
        List<OrderVo> ordersList = orderService.getOrderList();
        return Result.success(ordersList);
    }

    /**
     * 根据订单编号查询订单信息
     * @param number 订单编号
     * @return 订单信息
     */
    @GetMapping("/detail")
    public Result<OrderDetailVo> getOrderDetail(String number){
        OrderDetailVo orderDetail;
        try {
            orderDetail = orderService.getOrderDetail(number);
        } catch (BusinessException e) {
            return Result.error("订单异常，请联系管理员");
        }
        return Result.success(orderDetail);
    }
}
